package com.huijinhui.wlmtsys.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.huijinhui.wlmtsys.constant.MessageConstant;
import com.huijinhui.wlmtsys.constant.StatusConstant;
import com.huijinhui.wlmtsys.enums.AppHttpCodeEnum;
import com.huijinhui.wlmtsys.exception.LoginFailedException;
import com.huijinhui.wlmtsys.exception.PasswordErrorException;
import com.huijinhui.wlmtsys.mapper.AdminMapper;
import com.huijinhui.wlmtsys.mapper.TeamsMapper;
import com.huijinhui.wlmtsys.mapper.UserMapper;
import com.huijinhui.wlmtsys.pojo.dtos.AdUserDto;
import com.huijinhui.wlmtsys.pojo.dtos.LoginFormDTO;
import com.huijinhui.wlmtsys.pojo.dtos.PageDTO;
import com.huijinhui.wlmtsys.pojo.dtos.ResponseResult;
import com.huijinhui.wlmtsys.pojo.entity.*;
import com.huijinhui.wlmtsys.pojo.vo.AdminLoginVO;
import com.huijinhui.wlmtsys.properties.WeChatProperties;
import com.huijinhui.wlmtsys.service.*;
import com.huijinhui.wlmtsys.utils.BeanUtils;
import com.huijinhui.wlmtsys.utils.CollUtils;
import com.huijinhui.wlmtsys.utils.HttpClientUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.security.auth.login.AccountLockedException;
import javax.security.auth.login.AccountNotFoundException;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.*;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class AdminServiceImpl extends ServiceImpl<AdminMapper, AdUser> implements AdminService {

    final AdminMapper adminMapper;
    final NewsService newsService;
    final ProjectsService projectsService;
    final EmployService employService;
    final TeamsMapper teamsMapper;
    private final FileStorageService fileStorageService;

    /**
     * @param adUserDto
     * @return
     */
    @Override
    public AdUser login(AdUserDto adUserDto) {
        String username = adUserDto.getName();
        String password = adUserDto.getPassword();

        //1、根据用户名查询数据库中的数据
//        Employee employee = employeeMapper.getByUsername(username);
        AdUser user = lambdaQuery().eq(AdUser::getName, username).last("LIMIT 1").one();

        //2、处理各种异常情况（用户名不存在、密码不对、账号被锁定）
        if (user == null) {
            //账号不存在
            throw new LoginFailedException(MessageConstant.ACCOUNT_NOT_FOUND);
        }

        //密码比对
        // 对前端的密码进行md5加密，然后再进行比对
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        if (!password.equals(user.getPassword())) {
            //密码错误
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }
        user.setLoginTime(LocalDateTime.now());
        this.lambdaUpdate().eq(AdUser::getId, user.getId()).set(AdUser::getLoginTime, LocalDateTime.now()).update();

        //3、返回实体对象
        return user;
    }

    /**
     * @return
     */
    @Override
    public ResponseResult queryAll() {
        Counts counts = new Counts();
        counts.setNewsNum(newsService.count());
        counts.setProjectNum(projectsService.count());
        counts.setEmployNum(employService.count());
//        counts.setTeamNum(teamsService.count());
        QueryWrapper<WlmtsysTeams> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("DISTINCT name"); // 选择去重的字段
        counts.setTeamNum(teamsMapper.selectCount(queryWrapper));
        return ResponseResult.okResult(counts);
    }

    /**
     * @param multipartFile
     * @param imageId
     * @return
     */
    @Override
    public ResponseResult upload1(MultipartFile multipartFile, Integer imageId) {
        //1.检查参数
        if (multipartFile == null || multipartFile.getSize() == 0 || imageId == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //2.上传图片到minIO中
        String fileName = UUID.randomUUID().toString().replace("-", "");
        //aa.jpg
        String originalFilename = multipartFile.getOriginalFilename();
        String postfix = originalFilename.substring(originalFilename.lastIndexOf("."));
        String fileId = null;
        try {
            fileId = fileStorageService.uploadImgFile("", fileName + postfix, multipartFile.getInputStream());
            log.info("上传图片到MinIO中，fileId:{}", fileId);
        } catch (IOException e) {
            e.printStackTrace();
            log.error("WmMaterialServiceImpl-上传文件失败");
        }

        //3.更新数据库
        this.lambdaUpdate().eq(AdUser::getId, imageId).set(AdUser::getImage1, fileId).update();
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * @param multipartFile
     * @param imageId
     * @return
     */
    @Override
    public ResponseResult upload2(MultipartFile multipartFile, Integer imageId) {
        //1.检查参数
        if (multipartFile == null || multipartFile.getSize() == 0 || imageId == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //2.上传图片到minIO中
        String fileName = UUID.randomUUID().toString().replace("-", "");
        //aa.jpg
        String originalFilename = multipartFile.getOriginalFilename();
        String postfix = originalFilename.substring(originalFilename.lastIndexOf("."));
        String fileId = null;
        try {
            fileId = fileStorageService.uploadImgFile("", fileName + postfix, multipartFile.getInputStream());
            log.info("上传图片到MinIO中，fileId:{}", fileId);
        } catch (IOException e) {
            e.printStackTrace();
            log.error("WmMaterialServiceImpl-上传文件失败");
        }

        //3.更新数据库
        this.lambdaUpdate().eq(AdUser::getId, imageId).set(AdUser::getImage2, fileId).update();
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * @param multipartFile
     * @param imageId
     * @return
     */
    @Override
    public ResponseResult upload3(MultipartFile multipartFile, Integer imageId) {
        //1.检查参数
        if (multipartFile == null || multipartFile.getSize() == 0 || imageId == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //2.上传图片到minIO中
        String fileName = UUID.randomUUID().toString().replace("-", "");
        //aa.jpg
        String originalFilename = multipartFile.getOriginalFilename();
        String postfix = originalFilename.substring(originalFilename.lastIndexOf("."));
        String fileId = null;
        try {
            fileId = fileStorageService.uploadImgFile("", fileName + postfix, multipartFile.getInputStream());
            log.info("上传图片到MinIO中，fileId:{}", fileId);
        } catch (IOException e) {
            e.printStackTrace();
            log.error("WmMaterialServiceImpl-上传文件失败");
        }

        //3.更新数据库
        this.lambdaUpdate().eq(AdUser::getId, imageId).set(AdUser::getImage3, fileId).update();
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * @param multipartFile
     * @param imageId
     * @return
     */
    @Override
    public ResponseResult upload4(MultipartFile multipartFile, Integer imageId) {
        //1.检查参数
        if (multipartFile == null || multipartFile.getSize() == 0 || imageId == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //2.上传图片到minIO中
        String fileName = UUID.randomUUID().toString().replace("-", "");
        //aa.jpg
        String originalFilename = multipartFile.getOriginalFilename();
        String postfix = originalFilename.substring(originalFilename.lastIndexOf("."));
        String fileId = null;
        try {
            fileId = fileStorageService.uploadImgFile("", fileName + postfix, multipartFile.getInputStream());
            log.info("上传图片到MinIO中，fileId:{}", fileId);
        } catch (IOException e) {
            e.printStackTrace();
            log.error("WmMaterialServiceImpl-上传文件失败");
        }

        //3.更新数据库
        this.lambdaUpdate().eq(AdUser::getId, imageId).set(AdUser::getImage4, fileId).update();
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * @return
     */
    @Override
    public ResponseResult getLabIntro() {
        AdUser user = this.lambdaQuery().eq(AdUser::getId, 100).one();
        return ResponseResult.okResult(user);
    }

    /**
     * @return
     */
    @Override
    public List<AdUser> queryEmployPage() {
        List<AdUser> list = this.lambdaQuery().eq(AdUser::getStatus, 1)
                .orderByDesc(AdUser::getLoginTime)
                .list();
        if (CollUtils.isEmpty(list)) {
            return null;
        }
        return list;
    }

    /**
     * @param adUser
     */
    @Override
    public void updateLabInfo(AdUser adUser) {
        String password = adUser.getPassword();
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        if ((password!= null && password.length() > 0)){
            adUser.setPassword(password);
            updateById(adUser);
        }

    }
}




